package com.yequan.hbb.view.fragment.lhp;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.yequan.hbb.R;
import com.yequan.hbb.adapter.SearchAdapter;
import com.yequan.hbb.app.MyApplication;
import com.yequan.hbb.customview.ClearEditText;
import com.yequan.hbb.entries.EntrySearch;
import com.yequan.hbb.entries.LearnHP;
import com.yequan.hbb.entries.QuestionSearch;
import com.yequan.hbb.entries.SearchEntry;
import com.yequan.hbb.servers.Servers;
import com.yequan.hbb.utils.ServerUtil;
import com.yequan.hbb.view.MainActivity;

import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/10/14.
 */

public class SearchFragment extends Fragment implements Action1<EntrySearch>,  SwipeRefreshLayout.OnRefreshListener, TextWatcher {

    private SearchAdapter searchAdapter;
    private ClearEditText clearEditText;
    private RecyclerView recycler_history_view;
    private SearchAdapter adapter_1;
    private View pro;
    private View base_history;
    private SwipeRefreshLayout swipeRefreshLayout;
    private int flag;
    private Servers request;
    private String keys;
    private int page;
    private int pageSize;
    private Subscriber<EntrySearch> subscriber;
    private boolean isLoadingMore;

    public SearchFragment() {
    }

    public static SearchFragment getInstance(String keywords, int flag) {

        SearchFragment searchFragment = new SearchFragment();

        Bundle bundle = new Bundle();
        bundle.putString("keys", keywords);
        bundle.putInt("flag", flag);
        searchFragment.setArguments(bundle);
        return searchFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.wl_l_hp_search_2, container, false);
        return inflate;
    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        clearEditText = ((ClearEditText) view.findViewById(R.id.edit_search));
      /*
        recyclerView = ((RecyclerView) view.findViewById(R.id.recyler_view));
        searchAdapter = new SearchAdapter(getContext());
        recyclerView.setAdapter(searchAdapter);
      */
        clearEditText.addTextChangedListener(this);
        Bundle bundle = getArguments();
        keys = bundle.getString("keys");
        flag = bundle.getInt("flag");
        request = ServerUtil.createHttpRequest(Servers.class);
        Observable<SearchEntry> searchMainInfo = request.getSearchMainInfo();
        recycler_history_view = ((RecyclerView) view.findViewById(R.id.search_recycler_view));
        final LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        swipeRefreshLayout = ((SwipeRefreshLayout) view.findViewById(R.id.swip_refresh));
        recycler_history_view.setLayoutManager(manager);
        if (!TextUtils.isEmpty(keys)) {
            base_history = view.findViewById(R.id.base_history);
            base_history.setVisibility(View.INVISIBLE);
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            pro = view.findViewById(R.id.wait_pro);
            pro.setVisibility(View.VISIBLE);
            swipeRefreshLayout.setOnRefreshListener(this);
            recycler_history_view.setVisibility(View.VISIBLE);
            adapter_1 = new SearchAdapter<EntrySearch.DataBeanH.SearchBean.ListBean.RecipeBean.DataBean>(getContext());
            recycler_history_view.setAdapter(adapter_1);

            recycler_history_view.addOnScrollListener(new RecyclerView.OnScrollListener() {

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    int lastVisibleItem =  manager.findLastVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();
                    //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                    // dy>0 表示向下滑动
                    if (lastVisibleItem >= totalItemCount - 4 && dy > 0) {
                        if(isLoadingMore){
                        } else{
                            //loadPage();//这里多线程也要手动控制isLoadingMore
                            isLoadingMore = true;
                            Observable<EntrySearch> entrySearch = request.getEntrySearch(keys, page, pageSize);
                            entrySearch.subscribe(subscriber);
                        }
                    }
                }
            });
            view.findViewById(R.id.wait_pro).setVisibility(View.VISIBLE);
            if (flag == 0) {
                //搜索关键字
                Observable<QuestionSearch> questionSearch = request.getQuestionSearch(keys);
                questionSearch.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                        .subscribe(new Subscriber<QuestionSearch>() {
                            @Override
                            public void onCompleted() {

                            }
                            @Override
                            public void onError(Throwable e) {

                            }
                            @Override
                            public void onNext(QuestionSearch entrySearch) {

                            }
                        });

            } else if (flag == 1) {
                //主页分类条过来的
                page = 0;
                pageSize = 20;
                Observable<EntrySearch> entrySearch = request.getEntrySearch(keys, page, pageSize);
                subscriber = new Subscriber<EntrySearch>() {
                    @Override
                    public void onCompleted() {


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(EntrySearch entrySearch) {
                        clearEditText.setText(keys);
                        pro.setVisibility(View.INVISIBLE);
                        adapter_1.addAll(entrySearch.getData().getSearch().getList().getRecipe().getData());
                       /* List<EntrySearch.DataBeanH.SearchBean.ListBean.RecipeBean.DataBean> data = entrySearch.getData().getSearch().getList().getRecipe().getData();
                        for (EntrySearch.DataBeanH.SearchBean.ListBean.RecipeBean.DataBean dataBean : data) {

                            adapter_1.add(dataBean);
                        }*/
                        isLoadingMore=!isLoadingMore;
                        page++;
                    }
                };
                entrySearch.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                        .subscribe(subscriber);
            }
        } else {
            searchMainInfo.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<SearchEntry>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(SearchEntry searchEntry) {
                            //  searchAdapter.add(searchEntry);
                            TextView tv1 = (TextView) view.findViewById(R.id.tv1);
                            TextView tv2 = (TextView) view.findViewById(R.id.tv2);
                            TextView tv3 = (TextView) view.findViewById(R.id.tv3);
                            TextView tv4 = (TextView) view.findViewById(R.id.tv4);
                            TextView tv5 = (TextView) view.findViewById(R.id.tv5);
                            TextView tv6 = (TextView) view.findViewById(R.id.tv6);
                            TextView tv7 = (TextView) view.findViewById(R.id.tv7);
                            TextView tv8 = (TextView) view.findViewById(R.id.tv8);
                            TextView tv9 = (TextView) view.findViewById(R.id.tv9);
                            List<SearchEntry.DataBean.PopularSearchBean> popularSearch = searchEntry.getData().getPopularSearch();
                            tv1.setText(popularSearch.get(0).getKeyword());
                            tv2.setText(popularSearch.get(1).getKeyword());
                            tv3.setText(popularSearch.get(2).getKeyword());
                            tv4.setText(popularSearch.get(3).getKeyword());
                            tv5.setText(popularSearch.get(4).getKeyword());
                            tv6.setText(popularSearch.get(5).getKeyword());
                            tv7.setText(popularSearch.get(6).getKeyword());
                            tv8.setText(popularSearch.get(7).getKeyword());
                            tv9.setText(popularSearch.get(8).getKeyword());
                        }
                    });
        }
    }

    @Override
    public void onDestroy() {
        MyApplication.main.findViewById(R.id.main_rg).setVisibility(View.VISIBLE);
        MyApplication.main.findViewById(R.id.rl).setVisibility(View.VISIBLE);
        super.onDestroy();
    }

    /**
     * Called when a swipe gesture triggers a refresh.
     */
    @Override
    public void onRefresh() {
        if (flag==0){

        }else if (flag==1){
            Observable<EntrySearch> entrySearch = request.getEntrySearch(keys, 0, pageSize);
            entrySearch.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
            .subscribe(new Subscriber<EntrySearch>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(EntrySearch entrySearch) {
                    // searchAdapter.clear();
                    // searchAdapter.addAll(entrySearch.getData().getSearch().getList().getRecipe().getData());
                    swipeRefreshLayout.setRefreshing(false);

                }
            });
        }

    }



    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }


    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }


    @Override
    public void afterTextChanged(Editable s) {
        String s1 = s.toString();
        page=0;
        Observable<EntrySearch> entrySearch = request.getEntrySearch(s1, page, pageSize);
        entrySearch.subscribe(this);
    }

    @Override
    public void call(EntrySearch entrySearch) {

    }
}
